{{define "index.html"}}
<!--Embed the header.html template at this location-->
{{ template "header" .}}

<br>
<div style="text-align:center;"><h2>WebRTC Remote Control</h2></div>
<hr style="background-color: #213F99;width: 100px;margin-left: auto;margin-right: auto;">
<div style="text-align:center;"><p class="lead">基于WebRTC的实时远程控制系统,支持视频监控、远程控制与SSH登录</p></div>

<div class="container"> 
  <div class="row">
    <div class="col-md-4 offset-md-4">
      <div class="row">

        <div class="col-8 px-0"> 
          <div class="dropdown">
            <button class="btn btn-outline-secondary btn-block dropdown-toggle" id="dropdown_menu_link" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" style="overflow:hidden; text-overflow:ellipsis;">请选择你要连接的设备</button>
            <div class="dropdown-menu" style="min-width: 100%" aria-labelledby="dropdown_menu_link" id="devices_list"></div>
          </div>
        </div>

        <div class="col-1 px-0">
          <button type="button" class="btn btn-outline-dark" onclick="getDevices()" id="device_refresh"><i class="fas fa-sync"></i></button>
        </div>

        <div class="col-3 pr-0">
            <button type="button" class="btn btn-block btn-primary disabled" onclick="startSession()" id="connection_btn" disabled>连接</button>
        </div>

      </div>
      <div class="row">
          <div class="col-12 px-1">
            <small id="loger"></small>
          </div>
      </div>
    </div>
  </div>
</div>

<!-- Modal -->
<div class="modal fade" id="login_modal" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">登录</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <label for="device_id_show">Device ID:</label>
                <input type="text" class="form-control" id="device_id_show" readonly>
                <label for="password_show">Password</label>
                <input type="password" class="form-control" id="password_input">
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" onclick="submitPassword()">确定</button>
            </div>
        </div>
    </div>
</div>

{{ template "cards" .}}

<script>
var wsClient = null;

$(window).on('beforeunload', function(){
    wsClient.close();
});
function initWebsocket(){
    wsClient = new WebSocket("ws://"+document.location.host+"/offer");

    wsClient.onopen = function() {
        //成功连接到服务器
        console.log("connected to server");
        initWebRTC();
    }

    wsClient.onclose = function(e) {
        btnClose();
        console.log("connection closed (" + e.code + ")");
    }

    wsClient.onmessage = function(e) {
        console.log("message received: " + e.data);
        var obj = JSON.parse(e.data);

        if(obj.type == "error"){
            log(obj.msg);
            stopSession();
        }else if(obj.type == "answer"){
            var remoteSessionDescription = obj.data;
            if (remoteSessionDescription === '') {
                alert('Session Description must not be empty');
            }

            try {
                pc.setRemoteDescription(new RTCSessionDescription(JSON.parse(atob(remoteSessionDescription))));
                btnOpen();
            } catch (e) {
                alert(e);
            }
        }else if(obj.type == "password"){
            $('#login_modal').modal('show');
            $('#device_id_show').val(obj.device_id);
            $('#password_show').val("");
        }
    }
}

function submitPassword(){
    $('#login_modal').modal('hide');
    var content = new Object();
    content["type"]="password";
    content["data"]=$('#password_input').val();
    wsClient.send(JSON.stringify(content));
}
</script>

<script>
var pc;
var trackCache;
var trackFlag = true;

function initWebRTC(){
    pc = new RTCPeerConnection({
        iceServers: [
            {
                urls: 'stun:118.89.111.54:3478'
            }, {
                url: "turn:118.89.111.54:3478",
                username: "leizhh",
                credential: "leizhh"
            }
        ]
    });

    pc.ontrack = function (event) {
        if(trackFlag){
            trackCache = event.track;
            trackFlag = false;
        }else{
            var el = document.getElementById('remote-video')
            resStream = event.streams[0].clone()
            resStream.addTrack(trackCache)
            el.srcObject = resStream
        }
    }

    initSSH();
    initControl();

    pc.oniceconnectionstatechange = e => log(pc.iceConnectionState)
    pc.onicecandidate = event => {
        if (event.candidate === null) {
            var localSessionDescription = btoa(JSON.stringify(pc.localDescription));
            var content = new Object();
            content["type"]="offer";
            content["device_id"]=$("#dropdown_menu_link").attr("value");
            content["data"]=localSessionDescription;
            wsClient.send(JSON.stringify(content));
            //console.log("localDescription:",btoa(JSON.stringify(pc.localDescription)));
        }
    }

    // Offer to receive 1 audio, and 1 video tracks
    pc.addTransceiver('audio', {'direction': 'sendrecv'})
    pc.addTransceiver('video', {'direction': 'sendrecv'})
    pc.createOffer().then(d => pc.setLocalDescription(d)).catch(log)
}

function log(msg){
    $("#loger").html(msg);
}
</script>

<script>
var DevicesList = new Array();

function getDevices(){
    $("#devices_list").empty();
    $("#dropdown_menu_link").text("请选择你要连接的设备");
    $("#dropdown_menu_link").attr("value","");
    var el = document.getElementById('remote-video');
    el.srcObject = null;

    $.ajax({
        type:"GET",
        url:"/devices",
        dataType:"json", 
        success:function(data){
            if(data.data == null){
                $("#devices_list").prepend("<a class=\"dropdown-item disabled\" onclick=\"dropdownShow($(this).text())\">当前没有设备在线</a>");                            
            }else{
                $.each(data.data, function (index, value) {      
                    DevicesList[value.device_id] = value.using;
                    name = value.device_id +(value.using?"<font color=\"red\">[使用中]</font>":"<font color=\"green\">[可用]</font>");
                    $("#devices_list").prepend("<a class=\"dropdown-item\" onclick=\"dropdownShow($(this))\" value=\""+value.device_id+"\">"+name+"</a>");  
                    console.log(name);                   
                });                         
            }
        },
        error:function(jqXHR){
            console.log("Error: "+jqXHR.status);
        }
    });
}

$(document).ready(function() {
    getDevices();
    initTerm();
});

function dropdownShow(a) {
    $("#dropdown_menu_link").text(a.text());
    $("#dropdown_menu_link").attr("value",a.attr("value"));
    if(DevicesList[a.attr("value")] == true){
        $("#connection_btn").addClass("disabled");
        $("#connection_btn").attr("disabled", true); 
    }else{
        $("#connection_btn").removeClass("disabled");
        $("#connection_btn").attr("disabled", false); 
    }
}

function startSession(){
    initWebsocket();
}

function stopSession(){
    wsClient.close();
    btnClose();
}

function btnOpen(){
    $("#connection_btn").text("断开");
    $("#connection_btn").removeClass("btn_primary");
    $("#connection_btn").addClass("btn-danger");
    $("#connection_btn").attr("onclick","stopSession()");
    $("#dropdown_menu_link").addClass("disabled");
    $("#dropdown_menu_link").attr("disabled", true); 
    $("#device_refresh").addClass("disabled");
    $("#device_refresh").attr("disabled", true); 
}

function btnClose(){
    $("#connection_btn").text("连接");
    $("#connection_btn").removeClass("btn-danger");
    $("#connection_btn").addClass("btn_primary");
    $("#connection_btn").attr("onclick","startSession()");
    $("#connection_btn").addClass("disabled");
    $("#connection_btn").attr("disabled", true); 
    $("#dropdown_menu_link").removeClass("disabled");
    $("#dropdown_menu_link").attr("disabled", false); 
    $("#device_refresh").removeClass("disabled");
    $("#device_refresh").attr("disabled", false); 
    $("#control-send").attr("disabled", true);
}
</script>

<!--Embed the footer.html template at this location-->
{{ template "footer" .}}
{{end}}